package hander

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/google/uuid"
	"math/rand"
	"rpc-server/basic/global"
	"rpc-server/internal/common/queue"
	"rpc-server/internal/elas"
	"rpc-server/internal/model"
	"rpc-server/pkg"
	"time"

	__ "rpc-server/proto"
)

type UserServer struct {
	__.UnimplementedUserServer
}

func (c *UserServer) SendSms(_ context.Context, in *__.SendSmsRequest) (*__.SendSmsResponse, error) {
	code := rand.Intn(9000) + 1000
	global.Rdb.Set(context.Background(), "SendSms"+in.Tel, code, time.Minute*3)
	return &__.SendSmsResponse{}, nil
}

func (c *UserServer) Login(_ context.Context, in *__.LoginRequest) (*__.LoginResponse, error) {

	var user model.User
	global.DB.Where("tel=?", in.Tel).Find(&user)
	if user.Id == 0 {
		return nil, fmt.Errorf("用户未注册")
	}
	get := global.Rdb.Get(context.Background(), "SendSms"+in.Tel)
	if get.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("验证码错误")
	}

	return &__.LoginResponse{
		Id: int64(user.Id),
	}, nil

}

func (c *UserServer) SyncGoods(_ context.Context, in *__.SyncGoodsRequest) (*__.SyncGoodsResponse, error) {

	elas.SyncGoodsToEs()
	return &__.SyncGoodsResponse{}, nil

}

//	func SyncGoodsToEs() {
//		var wg sync.WaitGroup
//		var goodsList []*models.Goods
//		var g models.Goods
//		goodsList, _ = g.List()
//
//		// 1. 从数据库中查询所有的商品
//		for _, goods := range goodsList {
//			wg.Add(1)
//
//			go func(goods *models.Goods) {
//				defer wg.Done()
//
//				// Build the request body.
//				data, err := json.Marshal(goods)
//				if err != nil {
//					log.Fatalf("Error marshaling document: %s", err)
//				}
//
//				// Set up the request object.
//				req := esapi.IndexRequest{
//					Index:      "goods",
//					DocumentID: strconv.Itoa(int(goods.ID)),
//					Body:       bytes.NewReader(data),
//					Refresh:    "true",
//				}
//
//				// 2. 将商品数据同步到ES中
//				res, err := req.Do(context.Background(), Es)
//				if err != nil {
//					log.Fatalf("Error getting response: %s", err)
//				}
//				defer res.Body.Close()
//			}(goods)
//		}
//		wg.Wait()
//
// }
//
//	func SearchGoods(keyword string) (goodsList []*goods.GoodsItem) {
//		// 1. 从ES中查询商品
//		var buf bytes.Buffer
//		var query map[string]interface{} // 定义查询条件
//		if keyword != "" {
//			query = map[string]interface{}{
//				"query": map[string]interface{}{
//					"match": map[string]interface{}{
//						"GoodsTitle": keyword,
//					},
//				},
//			}
//		} else {
//			query = map[string]interface{}{
//				"query": map[string]interface{}{
//					"match_all": map[string]interface{}{},
//				},
//			}
//		}
//
//		// 2. 将查询条件转换为JSON格式
//		if err := json.NewEncoder(&buf).Encode(query); err != nil {
//			log.Fatalf("Error encoding query: %s", err)
//		}
//
//		// 3. 执行查询
//		res, err := Es.Search(
//			Es.Search.WithContext(context.Background()),
//			Es.Search.WithIndex("goods"),
//			Es.Search.WithBody(&buf),
//			Es.Search.WithTrackTotalHits(true),
//			Es.Search.WithPretty(),
//		)
//		if err != nil {
//			log.Fatalf("Error getting response: %s", err)
//		}
//		defer res.Body.Close()
//
//		//fmt.Println(res)
//		var r map[string]interface{}
//		if err = json.NewDecoder(res.Body).Decode(&r); err != nil {
//			log.Fatalf("Error parsing the response body: %s", err)
//		}
//
//		//fmt.Println(r)
//		for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
//			source := hit.(map[string]interface{})["_source"].(map[string]interface{})
//
//			goodsId := source["ID"].(float64)
//			goodsList = append(goodsList, &goods.GoodsItem{
//				GoodsId:    int64(goodsId),
//				GoodsTitle: "",
//				GoodsPrice: 0,
//				GoodsCover: "",
//			})
//		}
//
//		fmt.Println(goodsList)
//		return
//	}
func (c *UserServer) SearchGoods(_ context.Context, in *__.SearchGoodsRequest) (*__.SearchGoodsResponse, error) {

	list := elas.SearchGood(in.Keyword)

	return &__.SearchGoodsResponse{GoodsList: list}, nil

}
func (c *UserServer) ListGoods(_ context.Context, in *__.ListGoodsRequest) (*__.ListGoodResponse, error) {
	var good []model.Good
	var goodlist []*__.List
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	global.DB.Offset(int(offset)).Limit(int(pageSize)).Find(&good)

	for _, m := range good {
		goodlist = append(goodlist, &__.List{
			GoodsTitle: m.GoodsTitle,
			GoodsDesc:  m.GoodsDesc,
			GoodsPrice: float32(m.GoodsPrice),
			GoodsCover: m.GoodsCover,
		})
	}

	return &__.ListGoodResponse{List: goodlist}, nil

}
func (c *UserServer) AddGoods(_ context.Context, in *__.AddGoodsRequest) (*__.AddGoodsResponse, error) {
	good := model.Good{
		GoodsTitle:  in.GoodsTitle,
		GoodsDesc:   in.GoodsDesc,
		GoodsCover:  in.GoodsCover,
		GoodsPrice:  float64(in.GoodsPrice),
		GoodsStock:  int32(in.GoodsStock),
		CheckStatus: int(in.CheckStatus),
		Status:      int(in.Status),
	}

	if err := global.DB.Create(&good).Error; err != nil {
		return nil, fmt.Errorf("添加失败")
	}

	marshal, _ := json.Marshal(&good)

	global.Rdb.SetNX(context.Background(), "register", marshal, time.Minute*2)
	go queue.QueuePub("add", good)

	return &__.AddGoodsResponse{
		Code: 500,
		Msg:  "成功",
	}, nil

}
func (c *UserServer) Register(_ context.Context, in *__.RegisterRequest) (*__.RegisterResponse, error) {
	user := model.User{
		Username: in.Username,
		Password: pkg.EnPwdCode([]byte(in.Password)),
	}

	if err := global.DB.Create(&user).Error; err != nil {
		return nil, err
	}
	if user.Id != 0 {
		return nil, fmt.Errorf("用户已注册")
	}

	return &__.RegisterResponse{}, nil

}
func (c *UserServer) CreateGood(_ context.Context, in *__.CreateGoodRequest) (*__.CreateGoodResponse, error) {
	g := model.Good{}
	if err := global.DB.First(&g).Error; err != nil {
		return nil, fmt.Errorf("商品不存在")
	}

	if g.GoodsStock < int32(in.Num) {
		return nil, fmt.Errorf("库存不足")
	}

	OrderSn := uuid.NewString()
	price := g.GoodsPrice * float64(in.Num)
	totalAmount := fmt.Sprintf("%.2F", price)

	o := model.Order{
		OrderId:     int32(in.UserId),
		OrderNumber: OrderSn,
		OrderNum:    int32(in.Num),
		OrderPrice:  price,
		OrderStatus: 1,
	}

	if err := global.DB.Create(&o).Error; err != nil {
		return nil, fmt.Errorf("订单创建失败")
	}

	pay := pkg.AliPay(OrderSn, totalAmount, "商品支付")

	return &__.CreateGoodResponse{
		Url:     pay,
		OrderId: int64(o.Id),
	}, nil

}
